package com.geek.controller;

import com.geek.bean.BaseRespVo;
import com.geek.bean.PageData;
import com.geek.bean.vo.SaveAddressVO;
import com.geek.model.MarketAddress;
import com.geek.service.AddressService;
import io.swagger.annotations.Api;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * @author 小豪
 * @version 1.0
 * @description 地址模块
 * @date 2024-06-17 17:22
 */
@RestController
@RequestMapping("/wx/address")
@Api(tags = "收货地址模块")
public class WxAddressController {

    @Autowired
    private AddressService addressService;

    @GetMapping("list")
    public BaseRespVo list() {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            return BaseRespVo.fail("请先登录", 401);
        }
        Integer userId = (Integer) subject.getPrincipal();
        List<MarketAddress> addressList = addressService.list(userId);
        return BaseRespVo.ok(PageData.list(addressList));
    }

    @GetMapping("detail")
    public BaseRespVo detail(@RequestParam("id") Integer id) {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            return BaseRespVo.fail("请先登录", 401);
        }
        Integer userId = (Integer) subject.getPrincipal();
        MarketAddress marketAddress = addressService.addressDetail(userId, id);
        return BaseRespVo.ok(marketAddress);
    }

    @PostMapping("delete")
    public BaseRespVo delete(@RequestBody Map<String, Integer> map) {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            return BaseRespVo.fail("请先登录", 401);
        }
        Integer userId = (Integer) subject.getPrincipal();
        Integer id = map.get("id");
        int delete = addressService.deleteById(userId, id);
        if (delete == 0) {
            return BaseRespVo.fail("地址删除失败", 400);
        }
        return BaseRespVo.ok();
    }

    @PostMapping("save")
    public BaseRespVo save(@RequestBody SaveAddressVO saveAddress) {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {
            return BaseRespVo.fail("请先登录", 401);
        }
        Integer userId = (Integer) subject.getPrincipal();
        Integer id;
        if (saveAddress.getId() != 0) {
            id = addressService.update(userId, saveAddress);
        } else {
            id = addressService.save(userId, saveAddress);
        }
        return BaseRespVo.ok(id);
    }

}
